<script lang="ts" setup>
import { computed, reactive, ref, shallowRef, watch } from 'vue'
import { CloudUploadOutlined } from '@ant-design/icons-vue'
import type { Rule } from 'ant-design-vue/es/form'
import type { UploadFile } from 'ant-design-vue'
import type { AttendanceExcelItem, ExcelItem, OverTimeExcelItem } from '../../types/attendance'
import { AnalyzeExcel } from '../../utils/excel'
import { ATTENDANCE_EXCEL_KEY_MAP, OverTimeExcelKeyMap } from '../../enums/attendance'
import { handAttendanceOriginalData, handOTOriginalData, handleExcelData } from '../../utils/attendance'
import { modifyArrKeyName } from '../../utils/tools'
import { getEmployee } from '@/module/informationManagement/functions/core'
import type { Employee } from '@/module/informationManagement/types/employee'

const props = withDefaults(
  defineProps<{
    open?: boolean
    title?: string
  }>(),
  {
    open: false,
  },
)

const emits = defineEmits(['update:open', 'confirm'])

const openValue = computed<boolean>({
  get() {
    return props.open
  },
  set(val) {
    emits('update:open', val)
  },
})

// 表单
const formRef = ref()
const formData = reactive<Record<string, any>>({})
const employeeData = shallowRef<Employee[]>([])
// 表单验证规则
const rules: Record<string, Rule[]> = {
  attendance: [
    { required: true, message: '请上传考勤文件', trigger: 'change' },
  ],
}

function getEmployeeManagement() {
  // 获取人员管理列表
  getEmployee().then((res) => {
    if (res) {
      employeeData.value = res
    }
  })
}

// 关闭弹窗, 表单重置
watch(
  openValue,
  (val) => {
    if (val) {
      // 获取人员管理列表
      getEmployeeManagement()
    }
    else {
      // 重置表单
      formRef.value.resetFields()
    }
  },
)

function cancelUpload() {
  return false
}

/*
  @params file: 文件流
  @params ExcelMapKey: 映射KEY
  @params index 从第几行开始解析
  @return OrignExcelMap: 返回处理后的数据
*/
async function handleUploadExcelFile(file: UploadFile) {
  // 解析Excel
  const excelData = await AnalyzeExcel(file) as ExcelItem[]
  // 更改数组所有的KEY名
  const data: AttendanceExcelItem[] = modifyArrKeyName(excelData, ATTENDANCE_EXCEL_KEY_MAP)
  // 加班数据从第一项开始读取
  const excelList: AttendanceExcelItem[] = data && data.length > 2 ? data.slice(2) : []
  const originObj = handAttendanceOriginalData<AttendanceExcelItem>(excelList)
  return originObj
}

async function handleUploadOTExcelFile(file: UploadFile) {
  // 解析Excel
  const excelData = await AnalyzeExcel(file) as ExcelItem[]
  // 更改数组所有的KEY名
  const data: OverTimeExcelItem[] = modifyArrKeyName(excelData, OverTimeExcelKeyMap)
  // 加班数据从第一项开始读取
  const excelList: OverTimeExcelItem[] = data && data.length > 1 ? data.slice(1) : []
  const originObj = handOTOriginalData<OverTimeExcelItem>(excelList)
  return originObj
}

// 确认上传
function onConfirm() {
  formRef.value.validate()
    .then(() => {
      onSumit()
    })
    .catch(() => { })
}

// 提交数据
async function onSumit() {
  const { attendance, overtime } = formData
  let overTimeOriginObj = {}
  const attendanceOriginObj = await handleUploadExcelFile<AttendanceExcelItem>(attendance[0].originFileObj)

  if (overtime?.[0]) {
    overTimeOriginObj = await handleUploadOTExcelFile<OverTimeExcelItem>(overtime[0].originFileObj, OverTimeExcelKeyMap)
  }
  const {
    employeeList,
    workStatisticsData,
  } = handleExcelData(attendanceOriginObj, overTimeOriginObj, employeeData.value)

  emits('confirm', workStatisticsData, employeeList)
  openValue.value = false
}
</script>

<template>
  <Modal v-model:open="openValue" title="上传文件" @confirm="onConfirm">
    <a-form ref="formRef" :model="formData" :rules="rules">
      <a-form-item name="attendance">
        <a-upload-dragger
          v-model:file-list="formData.attendance" :before-upload="cancelUpload" accept=".xlsx,.xls"
          :max-count="1"
        >
          <p class="ant-upload-drag-icon">
            <CloudUploadOutlined />
          </p>
          <p class="ant-upload-text">
            点击或拖拽上传考勤文件
          </p>
        </a-upload-dragger>
      </a-form-item>

      <a-form-item name="overtime">
        <a-upload-dragger
          v-model:file-list="formData.overtime" :before-upload="cancelUpload" accept=".xlsx,.xls"
          :max-count="1"
        >
          <p class="ant-upload-drag-icon">
            <CloudUploadOutlined />
          </p>
          <p class="ant-upload-text">
            点击或拖拽上传加班文件
          </p>
        </a-upload-dragger>
      </a-form-item>
    </a-form>
  </Modal>
</template>
